package com.example.glideprogressiveloadimg

import com.bumptech.glide.load.Options
import com.bumptech.glide.load.model.GlideUrl
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.load.model.ModelLoaderFactory
import com.bumptech.glide.load.model.MultiModelLoaderFactory
import okhttp3.Call
import okhttp3.OkHttpClient
import java.io.InputStream

class OKHttpUrlLoader : ModelLoader<GlideUrl, InputStream> {

    private lateinit var client : Call.Factory

    constructor(client: Call.Factory) {
        this.client = client
    }

    override fun buildLoadData(
        model: GlideUrl,
        width: Int,
        height: Int,
        options: Options
    ): ModelLoader.LoadData<InputStream>? {

        return ModelLoader.LoadData(model, OkHttpStreamFetcher(client, model))

    }

    override fun handles(model: GlideUrl): Boolean {
        return true
    }

    public class Factory : ModelLoaderFactory<GlideUrl, InputStream> {

        companion object {
            private var internalClient: Call.Factory?=null

            fun getInternalClient() : Call.Factory {
                if (internalClient == null) {
                    synchronized(Factory.javaClass) {
                        if (internalClient == null) {
                            internalClient = OkHttpClient()
                        }
                    }
                }
                return internalClient!!
            }
        }

        var client:Call.Factory?=null

        constructor() {
            client = getInternalClient()
        }

        constructor(client : Call.Factory) {
            this.client = client
        }

        override fun build(multiFactory: MultiModelLoaderFactory): ModelLoader<GlideUrl, InputStream>{
            return OKHttpUrlLoader(client!!)
        }

        /** A lifecycle method that will be called when this factory is about to replaced.  */
        override fun teardown(){
            //none
        }
    }
}